import { Module, BadRequestException } from "@nestjs/common";
import { FileController } from "./file.controller";
import { MulterModule } from "@nestjs/platform-express";
import { diskStorage } from "multer";
import * as fs from "fs-extra";
import { UserModule } from "src/user/user.module";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { FileService } from "./service/file.service";
import { JwtModule } from "src/jwt/jwt.module";
import { FolderService } from "./service/folder.service";

@Module({
    imports: [
        JwtModule,
        UserModule,
        MulterModule.registerAsync({
            imports: [ConfigModule],
            inject: [ConfigService],
            useFactory: (configService: ConfigService) => ({
                storage: diskStorage({
                    destination: (req, file, cb) => {
                        // 注意字段顺序(文件字段放到最后),否则可能无法读取到其他字段
                        const dir = req.body.dir;
                        const defOutput = configService.get("UPLOAD_DIR");
                        try {
                            if (!dir) {
                                return cb(null, defOutput);
                            } else if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) {
                                // todo! 过滤一下路径吗
                                return cb(null, dir);
                            }
                            return cb(new BadRequestException(`not extist dir ${dir}`), defOutput);
                        } catch (error) {
                            return cb(error, defOutput);
                        }
                    },
                    filename: (req, file, cb) => {
                        let name = file.originalname;
                        if (!/[^\u0000-\u00ff]/.test(name)) {
                            name = Buffer.from(name, "latin1").toString("utf8");
                        }
                        return cb(null, name);
                    },
                }),
            }),
        }),
    ],
    controllers: [FileController],
    providers: [FileService, FolderService],
    exports: [FileService, FolderService],
})
export class FileModule {}
